import Koa from "koa"
import Router from 'koa-router'
import cors from '@koa/cors'
import {DataTypes, Sequelize,Op} from 'sequelize'
import bodyParser from "koa-bodyparser"


let app = new Koa();
let router = new Router();

app.use(cors());

app.use(bodyParser())



let sequelize = new Sequelize('soft1', 'root', '123456', {
    dialect: "mysql",
    host: 'localhost',
})

let Book = sequelize.define('book', {
    bookName: DataTypes.STRING,
    author: DataTypes.STRING,
    blurb: DataTypes.STRING
})

//同步类型到数据库
// await sequelize.sync();

// Book.bulkCreate([
//     {
//         bookName:"圈圈圆圆圈圈",
//         author:"年年天天年年",
//         blurb:"jj"
//     },
//     {
//         bookName:'不懂得爱恨情愁煎熬的我们',
//         author:'还以为相爱就像风云的善变',
//         blurb: 'jj'
//     }
// ])




router.get('/books', async (ctx) => {
    let books = await Book.findAll();
    ctx.body = {
        code: 1000,
        data: books,
        msg: '成功'
    }
})

router.post('/books',async (ctx)=>{
    let obj = ctx.request.body
    let res = await Book.create(obj)

    ctx.body = {
        code:1000,
        data:res,
        msg:'新增成功'
    }
})


router.delete('/books/:id', async (ctx) => {
    let id=ctx.params.id || 0
    let res=await Book.destroy({
        where:{
            id:id
        }
    })
    ctx.body={
        code:1000,
        data:res,
        msg:"删除成功"
    }
    
})

router.put('/books/:id', async (ctx) => {
    let id = ctx.params.id;
    let obj = ctx.request.body;
    let res = await Book.update(obj, {
        where: {
            id:id
}
})
    ctx.body={
        code:1000,
        data:res.data,
        msg:'修改成功'
    }
})


router.get('/book/:id',async (ctx)=>{
    let id = ctx.params.id||0;
    let res = await Book.findByPk(id);
    ctx.body={
        code:1000,
        data:res,
        msg:'获取指定信息成功'
    }
})





app.use(router.routes())
let appPort = 5000;
app.listen(appPort)
console.log(`http://localhost:${appPort}`)